package com.insight.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.vo.LoginUser;
import com.insight.modules.system.entity.SysUserAgent;
import com.insight.modules.system.service.ISysUserAgentService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

 /**
 * @Title: Controller
 * @Description: 用户代理人设置
 * @Author: jeecg-boot
 * @Date:  2019-04-17
 * @Version: V1.0
 */
 @RestController
 @RequestMapping("/sys/sysUserAgent")
 @Slf4j
 public class SysUserAgentController {

	 @Autowired
	 private ISysUserAgentService sysUserAgentService;

	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;

	 /**
	  * 分页查询用户代理人列表
	  *
	  * @param sysUserAgent 过滤条件封装实体，支持根据属性动态构造查询条件
	  * @param pageNo       页码，默认为1，从第一页开始
	  * @param pageSize     每页显示记录数，默认10条
	  * @param req          HttpServletRequest，用于获取请求中的参数
	  * @return 包含分页数据的统一响应结果对象，data部分为分页查询结果
	  */
	 @GetMapping(value = "/list")
	 public Result<IPage<SysUserAgent>> queryPageList(SysUserAgent sysUserAgent,
													  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
													  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
													  HttpServletRequest req) {
		 Result<IPage<SysUserAgent>> result = new Result<>();
		 // 根据请求参数和实体构造查询条件
		 QueryWrapper<SysUserAgent> queryWrapper = QueryGenerator.initQueryWrapper(sysUserAgent, req.getParameterMap());
		 // 构造分页对象
		 Page<SysUserAgent> page = new Page<>(pageNo, pageSize);
		 // 执行分页查询
		 IPage<SysUserAgent> pageList = sysUserAgentService.page(page, queryWrapper);
		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }

	 /**
	  * 添加新的用户代理人设置
	  *
	  * @param sysUserAgent 前端传递的用户代理人实体JSON对象
	  * @return 操作结果封装，成功时包含提示信息
	  */
	 @PostMapping(value = "/add")
	 public Result<SysUserAgent> add(@RequestBody SysUserAgent sysUserAgent) {
		 Result<SysUserAgent> result = new Result<>();
		 try {
			 if (sysUserAgent == null) {
				 result.error500("请求参数不能为空");
				 return result;
			 }
			 if (sysUserAgentService == null) {
				 result.error500("服务不可用");
				 return result;
			 }
			 sysUserAgentService.save(sysUserAgent);
			 result.success("代理人设置成功！");
		 } catch (Exception e) {
			 log.error("新增用户代理人失败: " + e.getMessage(), e);
			 result.error500("操作失败");
		 }
		 return result;
	 }

	 /**
	  * 编辑已存在的用户代理人设置
	  *
	  * @param sysUserAgent 包含ID的更新实体，ID用于定位待更新的记录
	  * @return 操作结果，更新成功返回成功提示，找不到记录或失败则返回错误信息
	  */
	 @PutMapping(value = "/edit")
	 public Result<SysUserAgent> edit(@RequestBody SysUserAgent sysUserAgent) {
		 Result<SysUserAgent> result = new Result<>();
		 // 根据ID查询数据库中的记录
		 SysUserAgent sysUserAgentEntity = sysUserAgentService.getById(sysUserAgent.getId());
		 if (sysUserAgentEntity == null) {
			 result.error500("未找到对应实体");
			 return result;
		 }
		 // 尝试更新记录
		 boolean ok = sysUserAgentService.updateById(sysUserAgent);
		 if (ok) {
			 result.success("代理人设置成功!");
		 } else {
			 result.error500("更新失败，请重试");
		 }
		 return result;
	 }

	 /**
	  * 根据ID删除用户代理人设置
	  *
	  * @param id 代理人设置记录的唯一标识ID
	  * @return 操作结果，成功返回删除成功提示，找不到记录或失败返回错误信息
	  */
	 @DeleteMapping(value = "/delete")
	 public Result<SysUserAgent> delete(@RequestParam(name = "id", required = true) String id) {
		 Result<SysUserAgent> result = new Result<>();
		 // 查询待删除记录是否存在
		 SysUserAgent sysUserAgent = sysUserAgentService.getById(id);
		 if (sysUserAgent == null) {
			 result.error500("未找到对应实体");
			 return result;
		 }
		 // 执行删除操作
		 boolean ok = sysUserAgentService.removeById(id);
		 if (ok) {
			 result.success("删除成功!");
		 } else {
			 result.error500("删除失败，请重试");
		 }
		 return result;
	 }

	 /**
	  * 批量删除用户代理人设置
	  *
	  * @param ids 多个记录ID组成的字符串，使用逗号分隔，如 "id1,id2,id3"
	  * @return 操作结果，成功返回删除成功提示，参数错误或异常返回错误信息
	  */
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<SysUserAgent> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		 Result<SysUserAgent> result = new Result<>();
		 if (ids == null || ids.trim().isEmpty()) {
			 result.error500("参数不识别！");
			 return result;
		 }
		 try {
			 List<String> idList = Arrays.asList(ids.split(","));
			 if (sysUserAgentService == null) {
				 result.error500("服务不可用");
				 return result;
			 }
			 sysUserAgentService.removeByIds(idList);
			 result.success("删除成功!");
		 } catch (Exception e) {
			 log.error("批量删除失败: " + e.getMessage(), e);
			 result.error500("删除失败，请重试");
		 }
		 return result;
	 }

	 /**
	  * 根据ID查询用户代理人设置详情
	  *
	  * @param id 用户代理人设置记录ID
	  * @return 查询结果，成功返回对应实体，找不到返回错误信息
	  */
	 @GetMapping(value = "/queryById")
	 public Result<SysUserAgent> queryById(@RequestParam(name = "id", required = true) String id) {
		 Result<SysUserAgent> result = new Result<>();
		 SysUserAgent sysUserAgent = sysUserAgentService.getById(id);
		 if (sysUserAgent == null) {
			 result.error500("未找到对应实体");
		 } else {
			 result.setResult(sysUserAgent);
			 result.setSuccess(true);
		 }
		 return result;
	 }

	 /**
	  * 根据用户名查询对应的代理人设置
	  *
	  * @param userName 用户登录名
	  * @return 代理人设置实体，找不到返回错误信息
	  */
	 @GetMapping(value = "/queryByUserName")
	 public Result<SysUserAgent> queryByUserName(@RequestParam(name = "userName", required = true) String userName) {
		 Result<SysUserAgent> result = new Result<>();
		 LambdaQueryWrapper<SysUserAgent> queryWrapper = new LambdaQueryWrapper<>();
		 queryWrapper.eq(SysUserAgent::getUserName, userName);
		 SysUserAgent sysUserAgent = sysUserAgentService.getOne(queryWrapper);
		 if (sysUserAgent == null) {
			 result.error500("未找到对应实体");
		 } else {
			 result.setResult(sysUserAgent);
			 result.setSuccess(true);
		 }
		 return result;
	 }

	 /**
	  * 导出用户代理人设置数据为Excel文件
	  *
	  * @param sysUserAgent 查询过滤条件，可为空
	  * @param request      HttpServletRequest，获取请求参数
	  * @return 返回Excel视图对象，供前端下载文件
	  */
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(SysUserAgent sysUserAgent, HttpServletRequest request) {
		 // Step.1 组装查询条件
		 QueryWrapper<SysUserAgent> queryWrapper = QueryGenerator.initQueryWrapper(sysUserAgent, request.getParameterMap());
		 // Step.2 调用服务获取数据列表
		 List<SysUserAgent> pageList = sysUserAgentService.list(queryWrapper);
		 // Step.3 创建Excel导出视图
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "用户代理人设置列表");
		 mv.addObject(NormalExcelConstants.CLASS, SysUserAgent.class);
		 // 获取当前登录用户信息作为导出人
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 ExportParams exportParams = new ExportParams("用户代理人设置列表数据", "导出人:" + user.getRealname(), "导出信息");
		 exportParams.setImageBasePath(upLoadPath);
		 mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }

	 /**
	  * 通过Excel文件导入用户代理人设置数据
	  *
	  * @param request  HttpServletRequest，包含上传文件流
	  * @param response HttpServletResponse，响应客户端请求
	  * @return 导入结果，包含成功条数或错误信息
	  */
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest != null ? multipartRequest.getFileMap() : null;
		 if (fileMap == null || fileMap.isEmpty()) {
			 return Result.error("文件导入失败！");
		 }
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();
			 if (file == null) {
				 continue;
			 }
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 if (sysUserAgentService == null) {
					 return Result.error("服务不可用");
				 }
				 List<SysUserAgent> listSysUserAgents = ExcelImportUtil.importExcel(file.getInputStream(), SysUserAgent.class, params);
				 if (listSysUserAgents != null) {
					 for (SysUserAgent sysUserAgentExcel : listSysUserAgents) {
						 if (sysUserAgentExcel != null) {
							 sysUserAgentService.save(sysUserAgentExcel);
						 }
					 }
				 }
				 return Result.ok("文件导入成功！数据行数：" + (listSysUserAgents != null ? listSysUserAgents.size() : 0));
			 } catch (Exception e) {
				 log.error("Excel导入失败: " + e.getMessage(), e);
				 return Result.error("文件导入失败！");
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (Exception e) {
					 log.error("关闭输入流异常", e);
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }
 }

